package cn.lzd.util

import java.io.File
import java.time.LocalDate

import scala.collection.JavaConverters._
import scala.collection.mutable

/**
  * Created by lzd on 2019/3/21.
  */
object FileUtils {

  def list2Map(javaList: java.util.List[File]): java.util.Map[String, java.util.List[String]] = {
    val list: List[File] = javaList.asScala.toList

    val map: Map[String, List[File]] = list.groupBy((x) => {
      val name: String = x.getName
      val split: Array[String] = name.split("_", -1)
      val builder = new StringBuilder()

      //去掉文件名的时间后缀
      var flag = true
      val year: Int = LocalDate.now().getYear

      for (i <- 0 to split.length - 1 if flag) {
        val value = split(i)
        if (value.startsWith(year.toString) || value.startsWith((year - 1).toString)) {
          flag = false
        } else {
          if (i == 0) {
            builder.append(value);
          } else {
            builder.append("_").append(value);
          }
        }
      }
      builder.toString()
    })
    val values: Map[String, List[String]] = map.mapValues((x) => {
      x.map((y) => {
        y.getAbsolutePath
      })
    })

    val resMap = new java.util.HashMap[String, java.util.List[String]]()

    for (elem <- values.keySet) {
      values.get(elem) match {
        case Some(value) => {
          val buffer: mutable.Buffer[String] = value.toBuffer
          resMap.put(elem, buffer.asJava)
        }
      }
    }
    resMap
  }
}

